<template>
  <PageLayout>
    <!-- 表格布局 -->
    <TableContainer height="calc(100vh - 100px)">
      <TableLayout
        ref="tableLayout"
        :loader="getList"
        tableRowKey="id"
        @reset="reset"
      >
        <!-- 头部搜索 -->
        <template #header>
          <el-form
            ref="queryRef"
            :inline="true"
            :model="queryParams"
            label-width="75px"
            class="header-form"
          >
            <el-form-item label="检验编码">
              <el-input
                v-model="queryParams.billCode"
                placeholder="请输入检验编码"
                clearable
                style="width: 160px"
                @input="handleQuery"
              />
            </el-form-item>

            <!-- <el-form-item label="检验类型">
                            <el-select
                                v-model="queryParams.billType"
                                placeholder="请选择检验类型"
                                style="width: 160px"
                                clearable
                                @change="handleQuery"
                            >
                                <el-option label="过程监造" value="1" />
                                <el-option label="现场验收" value="2" />
                            </el-select>
                        </el-form-item> -->

            <el-form-item label="物料编码">
              <el-input
                v-model="queryParams.materialCode"
                placeholder="请输入物料编码"
                clearable
                style="width: 160px"
                @input="handleQuery"
              />
            </el-form-item>

            <el-form-item label="物料名称">
              <el-input
                v-model="queryParams.materialName"
                placeholder="请输入物料名称"
                clearable
                style="width: 160px"
                @input="handleQuery"
              />
            </el-form-item>

            <el-form-item label="供应商">
              <el-input
                v-model="queryParams.suppliersName"
                placeholder="请输入供应商"
                clearable
                style="width: 160px"
                @input="handleQuery"
              />
            </el-form-item>

            <el-form-item label="方案名称">
              <el-input
                v-model="queryParams.schemeName"
                placeholder="请输入方案名称"
                clearable
                style="width: 160px"
                @input="handleQuery"
              />
            </el-form-item>

            <el-form-item label="检验结果">
              <el-select
                v-model="queryParams.billCheckResult"
                placeholder="请选择检验结果"
                style="width: 160px"
                clearable
                @change="handleQuery"
              >
                <el-option label="通过" value="1" />
                <el-option label="不通过" value="2" />
              </el-select>
            </el-form-item>
          </el-form>
        </template>

        <!-- 操作栏--左 -->
        <template #operator-left>
          <el-button type="warning" plain @click="handleExport"
            >导 出</el-button
          >
          <el-button type="primary" plain @click="handleAdd">新 增</el-button>
        </template>

        <!-- 操作栏-右 -->
        <template #operator-right>
          <div class="d-flex justify-space-between align-center">
            <tableOperatorSortCom
              :list="sortableHeader"
              isDrag
              paramKey="key"
              @column-change="handleColumnChange"
              @drag-end="handleDragEnd"
            ></tableOperatorSortCom>
            <VideoUpload helpId="site-accept_1746668340112" class="ml12" />
          </div>
        </template>
        <!-- 列表 -->
        <template #columns>
          <TableColumn label="序号" type="order" width="55"></TableColumn>
          <template v-for="column in tableHeader" :key="column.key">
            <TableColumn
              :label="column.label"
              :prop="column.key"
              :width="column.width"
              showOverflowTooltip
            >
              <template v-if="column.key == 'billCode'" #default="{ row }">
                <span class="link-title" @click="handlePreview(row)">
                  {{ row.billCode }}
                </span>
              </template>
              <template v-if="column.key == 'materialModel'" #default="{ row }">
                {{ row.materialModel || "-" }}
              </template>
              <template v-if="column.key == 'billType'" #default="{ row }">
                <span v-if="row.billType == '1'">过程监造</span>
                <span v-else-if="row.billType == '2'">现场验收</span>
                <span v-else>-</span>
              </template>
              <template
                v-if="column.key == 'billCheckResult'"
                #default="{ row }"
              >
                <span v-if="row.billCheckResult == '1'" class="right-status"
                  >通过</span
                >
                <span
                  v-else-if="row.billCheckResult == '2'"
                  class="wrong-status"
                  >不通过</span
                >
                <span v-else>-</span>
              </template>
              <template v-if="column.key == 'viewStatus'" #default="{ row }">
                <span v-if="row.viewStatus == '1'">未读</span>
                <span v-else-if="row.viewStatus == '2'">已读</span>
                <span v-else>-</span>
              </template>
              <template v-if="column.key == 'billStatus'" #default="{ row }">
                <span v-if="row.billStatus == '1'">暂存</span>
                <span v-else-if="row.billStatus == '2'">检验中</span>
                <span v-else-if="row.billStatus == '3'">完成</span>
                <span v-else>-</span>
              </template>
            </TableColumn>
          </template>
          <TableColumn fixed="right" label="操作" width="180">
            <template #default="{ row }">
              <TableAction>
                <TableActionItem @click="handleUpdate(row)">
                  {{ isCheckUser(row) == "2" ? "检验" : "编辑" }}
                </TableActionItem>
                <TableActionItem
                  @click="handleSupplyInspection(row)"
                  v-if="
                    !!row.billCheckResult &&
                    row.myCheckCount > 0 &&
                    showDelete(row)
                  "
                >
                  发起补检
                </TableActionItem>
                <TableActionItem
                  v-if="showDelete(row)"
                  type="danger"
                  @click="handleDelete(row)"
                >
                  删除
                </TableActionItem>
              </TableAction>
            </template>
          </TableColumn>
        </template>
      </TableLayout>
    </TableContainer>
  </PageLayout>
</template>

<script setup name="SiteAccept">
import { getInstanceList, deleteInstance } from "./service";
import { reactive } from "vue";
import columnConfig from "./column";
import tableOperatorSortCom from "@/components/admin/table-operator-sort";
import { useColumns } from "@/hooks/useColumns";
import useUserStore from "@/store/modules/user";
import auth from "@/plugins/auth";
import VideoUpload from "@/views/components/help/VideoUpload.vue";

const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
const userId = ref(useUserStore().userId);

const { tableHeader, sortableHeader, handleColumnChange, handleDragEnd } =
  useColumns("site-accept_1746668340112", columnConfig, "key", proxy);

onActivated(() => {
  if (route.query?.isRefresh) {
    reset();
    router.push({
      path: "/project/qualityManage/SiteAccept",
      query: {
        code: "PJM",
      },
    });
  }
});

const queryParams = reactive({
  billCode: null,
  billType: "2",
  materialCode: null,
  materialName: null,
  suppliersName: null,
  schemeName: null,
  billCheckResult: null,
  page: 1,
  pageSize: 20,
});

const tableLayout = ref();

// 判断是否为检验员
const isCheckUser = (row) => {
  const boolA = row.createUserId === userId.value; // 是否是创建者
  const boolB = auth.hasPermi("quality:check:super"); // 是否有权限
  if (boolA || boolB) {
    return "1"; // 不是检验员
  } else {
    return "2"; // 是检验员
  }
};

const showDelete = (row) => {
  const boolA = row.createUserId === userId.value; // 是否是创建者
  const boolB = auth.hasPermi("quality:check:super"); // 是否有权限
  return boolA || boolB;
};

function handleQuery() {
  queryParams.page = 1;
  tableLayout.value.refresh();
}

function reset() {
  queryParams.billCode = null;
  queryParams.billType = "2";
  queryParams.materialCode = null;
  queryParams.materialName = null;
  queryParams.suppliersName = null;
  queryParams.schemeName = null;
  queryParams.billCheckResult = null;
  queryParams.page = 1;
  queryParams.pageSize = 20;
  tableLayout.value.refresh();
}

async function getList(params) {
  const res = await getInstanceList({ ...queryParams, ...params });
  return { records: res.rows || [], total: res.total || 0 };
}

function handleExport() {
  proxy.download(
    "/project/checkBill/checkBillExport",
    {
      ...queryParams,
    },
    `检验单据_${new Date().getTime()}.xlsx`
  );
}

function handleAdd() {
  router.push({
    path: "SiteAcceptEdit",
    query: {
      code: "PJM",
      billType: "2",
    },
  });
}

function handleUpdate(row) {
  router.push({
    path: "SiteAcceptEdit",
    query: {
      id: row.id,
      code: "PJM",
      isChecker: isCheckUser(row),
    },
  });
}

function handleSupplyInspection(row) {
  router.push({
    path: "SiteAcceptSupplyInspection",
    query: {
      id: row.id,
      code: "PJM",
      isChecker: isCheckUser(row),
    },
  });
}

function handlePreview(row) {
  router.push({
    path: "SiteAcceptDetail",
    query: {
      id: row.id,
      code: "PJM",
    },
  });
}

async function handleDelete(row) {
  await proxy.$modal.confirm("确定删除？");
  const result = await deleteInstance(row.id);
  if (result.code === 200) {
    proxy.$modal.msgSuccess("删除成功");
    tableLayout.value.refresh();
  } else {
    proxy.modal.msgError(result.msg);
  }
}

function getTableData() {
  handleQuery();
}
</script>
<style lang="scss" scoped>
.header-form {
  .el-form-item {
    margin-bottom: 0;
  }
}
.link-title {
  color: #409eff;
  cursor: pointer;
  user-select: none;
}

.link-title:hover {
  color: #66b1ff;
}
.right-status {
  color: #67c23a;
}
.wrong-status {
  color: #f56c6c;
}
</style>
